<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter='20'>
        <!-- 文本框和搜索框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span='8'>
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 用户列表 -->
    <el-table :data="userList" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column prop="mg_state" label="用户状态">
        <!-- slot-scope="scope"  用于获取data数据 -->
        <template slot-scope="scope">
          <!-- {{scope.row.mg_state}} -->
          <el-switch v-model="scope.row.mg_state" @change="userStatusChanged(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width='180px'>
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button type="primary" icon="el-icon-edit" size='mini' @click="showEditDialog(scope.row.id)"></el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" icon="el-icon-delete" size='mini' @click="removeUserById(scope.row.id)"></el-button>
          <el-tooltip effect="dark" content="分配角色" placement="top" :enterable='false'>
            <!-- 分配角色 -->
            <el-button type="warning" icon="el-icon-setting" size='mini' @click="rolesSetting(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 4]" :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 添加用户按钮弹出的对话框 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="70px">
        <!-- prop 对应着校验规则 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息弹出的对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editdialogVisible" width="50%" @close="editFormClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop='email'>
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop='mobile'>
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的弹出框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogVisible" width="50%" @close='closeDialog'>
      <div>
        <p>当前的用户：{{this.userInfo.username}}</p>
        <p>当前的角色：{{this.userInfo.role_name}}</p>
        <P>分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </P>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      var checkEmail = (rule, value, callBack) => {
        var regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        // a.test(b) 检测b是否满足正则表达式a
        if (regEmail.test(value)) {
          //   合法的邮箱
          return callBack()
        }
        callBack(new Error('请输入合法的邮箱'))
      }
      var checkMobile = (rule, value, callBack) => {
        var regMobile = /^1[34578]\d{9}$/;
        // a.test(b) 检测b是否满足正则表达式a
        if (regMobile.test(value)) {
          //   合法的邮箱
          return callBack()
        }
        callBack(new Error('请输入合法的手机号'))
      }
      return {
        //   获取列表的参数对象
        queryInfo: {
          query: '',
          //   当前页码
          pagenum: 1,
          //   每页显示条数
          pagesize: 2
        },
        userList: [],
        total: 0,
        dialogVisible: false,
        // 添加用户的表单数据
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        // 添加用户的表单数据的验证规则
        addRules: {
          username: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }, {
            min: 3,
            max: 10,
            message: '用户名长度在3到10之间',
            trigger: 'blur'
          }],
          password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }, {
            min: 6,
            max: 15,
            message: '用户名长度在6到15之间',
            trigger: 'blur'
          }],
          email: [{
            validator: checkEmail,
            trigger: 'blur'
          }],
          mobile: [{
            validator: checkMobile,
            trigger: 'blur'
          }]
        },
        // 控制修改用户信息的显示与隐藏
        editdialogVisible: false,
        // 存放根据id 查询到的数据
        editForm: [],
        // 编辑用户的校验规则
        editFormRules: {
          email: [{
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          }, {
            validator: checkEmail,
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }, {
            validator: checkMobile,
            trigger: 'blur'
          }]
        },
        // 分配角色的弹框显示与隐藏
        roleDialogVisible: false,
        // 需要被分配新角色的用户信息
        userInfo: {},
        // 所有角色的数据列表
        rolesList: [],
        // 选中的角色名
        selectRoleId: ''
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        const {
          data: res
        } = await this.$http.get('users', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) return $message.error('数据获取失败')
        this.userList = res.data.users
        this.total = res.data.total
      },
      //   每页显示条数的改变
      handleSizeChange(newList) {
        this.queryInfo.pagesize = newList;
        //  重新获取数据
        this.getUserList()
      },
      //   监听 页码值 改变的事件
      handleCurrentChange(newPage) {
        console.log(newPage);
        this.queryInfo.pagenum = newPage;
        this.getUserList()
      },
      async userStatusChanged(newStatus) {
        //   console.log(newStatus);
        // 修改用户状态
        const {
          data: res
        } = await this.$http.put(`users/${newStatus.id}/state/${newStatus.mg_state}`)
        if (res.meta.status !== 200) {
          newStatus.mg_state = !newStatus.mg_state
          return this.$message.error("修改用户状态失败")
        }
        return this.$message.success("修改用户状态成功")

      },
      //   监听对话框的关闭事件
      addDialogClosed() {
        //  表单内容重置
        this.$refs.addFormRef.resetFields();
      },
      addUser() {
        //   表单预验证
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return;
          //   预验证成功，就可以发起添加用户的网络请求
          const {
            data: res
          } = await this.$http.post('users', this.addForm);
          console.log(res);
          if (res.meta.status !== 201) {
            this.$message.error('用户添加失败')
          }
          this.$message.success('用户添加成功');
          //   隐藏添加用户的对话框
          this.dialogVisible = false;
          // 重新获取数据
          this.getUserList();
        })
      },
      async showEditDialog(id) {
        const {
          data: res
        } = await this.$http.get('users/' + id)
        if (res.meta.status !== 200) return this.$message.error("信息查询错误")
        this.editForm = res.data
        this.editdialogVisible = true
      },
      //   表单关闭后，对表单内容进行重置，并消除校验结果
      editFormClosed() {
        this.$refs.editFormRef.resetFields();
      },
      // 修改表单后预验证并且提交
      editUserInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return;
          // 数据校验成功后，对数据进行存储
          const {
            data: res
          } = await this.$http.put('users/' + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          });

          if (res.meta.status !== 200) return this.$messgae.error('数据更新失败！')

          // 数据更新成功后的操作
          // 关闭对话框
          this.editdialogVisible = false
          // 刷新数据列表
          this.getUserList();
          // 提示更新数据成功
          this.$message.success('数据更新成功！')
        })
      },
      // 通过id 删除用户信息
      async removeUserById(id) {
        // 删除后的提示弹框
        const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          // catch 捕获取消的信息
        }).catch(err => err)

        // 弹框点击取消  confirmResult = 字符串 cancel
        // 弹框点击确认  confirmResult = 字符串 confirm
        if (confirmResult !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        // 删除操作
        const {
          data: res
        } = await this.$http.delete('users/' + id)

        if (res.meta.status !== 200) return this.$message.error('删除用户失败')
        this.$message.success('删除用户成功')
        this.getUserList()
      },
      // 分配角色
      async rolesSetting(role) {
        this.roleDialogVisible = true
        this.userInfo = role
        // 获取所有的角色的数据列表
        const {
          data: res
        } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error('获取数据失败')
        }
        this.rolesList = res.data
        console.log(this.rolesList);
      },
      // 保存新分配的角色
      async saveRole() {
        // 判断是否选择的新的角色
        if (!this.selectRoleId) {
          this.$message.error('请选择新的角色')
        }
        const {
          data: res
        } = await this.$http.put('users/' + this.userInfo.id + '/role', {
          rid: this.selectRoleId
        })
        if (res.meta.status !== 200) {
          return this.$message.error('分配角色失败')
        }
        this.$message.success('分配角色成功')
        this.getUserList();
        this.roleDialogVisible = false
      },
      // 关闭分配角色的弹框后，置空内容
      closeDialog(){
          this.selectRoleId='',
          this.userInfo={}
      }
    }
  }

</script>

<style lang="less" scoped>

</style>
